import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder, Validators, AbstractControl } from '@angular/forms';
import { mobileValidator, equalValidator, mobileAsyncValidator} from '../validator/validators';


@Component({
  selector: 'app-reactive-rsgist',
  templateUrl: './reactive-rsgist.component.html',
  styleUrls: ['./reactive-rsgist.component.css']
})
export class ReactiveRsgistComponent implements OnInit {

 /* xxxxx(control: AbstractControl): {[key: string]: any} {     // 校验器方法
    return null;
  }*/

 // 移动到全局的方法里面去
 /* mobileValidator(control: FormControl): any {      // FormControl的校验
    let myreg = /^1[3|4|5|8][0-9]\d{4,8}$/;
    let valid = myreg.test(control.value);
    console.log("mobile的校验结果是：" + valid);
    return valid ? null : {mobile : true};
  }

  equalValidator(group: FormGroup): any {
    let password: FormControl = group.get("password") as FormControl;
    let pconfirm: FormControl = group.get("pconfirm") as FormControl;
    let valid: boolean = (password.value === pconfirm.value);
    console.log("密码校验结果：" + valid);
    return valid ? null : {equal : true};
  }*/

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    // 这就是数据结构
    /*this.formModel = new FormGroup({
      username: new FormControl(),
      mobile: new FormControl(),
      passwordsGroup: new FormGroup({
        password: new FormControl(),
        pconfirm: new FormControl()
      })
    });*/
    // 使用FormBuilder    和上面相同
    this.formModel = fb.group({
      username: ['', [Validators.required, Validators.minLength(6)]],   // 可以接收三个参数，第一个是初始值，第二个是校验方法（可以多个），第三个是异步的校验方法
      mobile: ['', mobileValidator, mobileAsyncValidator],
      passwordsGroup: fb.group({
        password: ['' , Validators.minLength(6)],
        pconfirm: ['']
      }, {validator: equalValidator})
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    let isValid: boolean = this.formModel.get("username").valid;
    console.log("username的校验结果："+isValid);
    let errors: any = this.formModel.get("username").errors;
    console.log("username的错误信息是："+ JSON.stringify(errors));
    if ( this.formModel.valid) {
      console.log(this.formModel.value);
    }
  }

}
